import requests
from bs4 import BeautifulSoup
import re
import random
import pymysql
import json


# 获取服务器的页面数据
def get_index(url, keyword):
    try:
        headers = {
            'token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxMzU0MDEyNDIyMiIsImlhdCI6MTYxODg5NTU4NiwiZXhwIjoxNjE4ODk5MTg2fQ.NCLzfUHpjKVUEW8AAWjmhSX9lfNo1tHt9J0C8yMrYLOofxzESQq4EO9CHYZ6F6xAp5UvKBp5xGu9goBdFyh6Mg'}
        print("获取网页："+url)
        respose = requests.post(url, headers=headers, data=keyword, timeout=29)

        if respose.status_code == 200:
            return respose.text
    except Exception as e:
        print('获取网页数据异常：'+str(e))
        return None


def get_index1(url):
    try:
        headers = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
            # 'accept-encoding': 'gzip, deflate, br',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Cache-Control': 'max-age=0',
            "sec-fetch-dest": "document",
            "sec-fetch-mode": "navigate",
            "sec-etch-site": "same - origin",
            "sec-fetch-user": "?1",
            'Upgrade-Insecure-Requests': '1',
            'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Mobile Safari/537.36'}
        response = requests.get(url, headers=headers, timeout=29)
        response.encoding = "gb2312"
        if response.status_code == 200:
            return response.text
    except Exception as e:
        print('获取网页数据异常：'+str(e))
        return None


def addData():
    f = open(r"D:\data.txt", encoding='utf-8')
    tup1 = ('type', 'question', 'answer1', 'answer2', 'answer')
    for lines in f:
        # lines = f.readline()
        res1 = lines.split()
        dd = dict.fromkeys(tup1)

        for index in range(len(tup1)):
            dd[tup1[index]] = res1[index]
        print(dd)
        print(get_index("http://shouhulife.vicp.cc/addquestion", dd))
    f.close()


def addData1():
    f = open(r"D:\data1.txt", encoding='utf-8')
    tup1 = ('type', 'question', 'answer1', 'answer2', 'answer')
    question =[]
    answer =[]
    for lines in f:
        # lines = f.readline()
        res1 = lines.split()

        # print(res1)
        # print(random.randint(0, len(res1)))
        question.append(res1[0])
        answer.append(res1[1])

        # print(get_index("http://shouhulife.vicp.cc/addquestion", dd))
    f.close()

    # 数据库操作
    conn = pymysql.connect('localhost', 'root', '123456')
    conn.select_db('answer_db')
    cur = conn.cursor()  # 获取游标


    dd = dict.fromkeys(tup1)
    for indexx in range(len(question)):
        for index in range(len(tup1)):
            # print(random.randint(0, len(res1)))
            # dd[tup1[index]] = res1[index]
            if index == 0:
                dd[tup1[index]] = "歇后语"
            elif index == 1:
                dd[tup1[index]] = question[indexx]
            elif index == 2:
                if random.randint(0, 1) == 0:
                    dd[tup1[2]] = answer[indexx]
                    dd[tup1[3]] = answer[random.randint(0, len(answer)-1)]
                else:
                    dd[tup1[2]] = answer[random.randint(0, len(answer)-1)]
                    dd[tup1[3]] = answer[indexx]

            elif index == 4:
                dd[tup1[index]] = answer[indexx]
        print(dd)

        sql = "insert into questionbank (type,question,answer1,answer2,answer) values('{}','{}','{}','{}','{}')".format(dd[tup1[0]], dd[tup1[1]], dd[tup1[2]], dd[tup1[3]], dd[tup1[4]])
        # print(sql)
        insert = cur.execute(sql)
        print('添加语句受影响的行数：', insert)
        # print(get_index("http://shouhulife.vicp.cc/addquestion", dd))

    cur.close()
    conn.commit()
    conn.close()


def mysql_db(dd):
    # 打开数据库连接，不指定数据库
    conn = pymysql.connect('localhost', 'root', '123456')
    conn.select_db('answer_db')
    cur = conn.cursor()  # 获取游标
    insert = cur.execute("insert into questionbank values(1,'tom',18)")
    print('添加语句受影响的行数：', insert)
    cur.close()
    conn.commit()
    conn.close()
    print('sql执行成功')


def getInfo(pages):
    text = get_index1("http://xhy.5156edu.com/html2/xhy_{}.html".format(pages))
    soup = BeautifulSoup(text, "html.parser")
    title_name = soup.findAll('tr', {'bgcolor': '#ffffff'})

    with open(r"D:\data1.txt", "a", encoding='utf-8') as f:
        for value in title_name:
            # print(value.text)
            res1 = value.text.split()
            # print(res1[0] + "======" + res1[1])
            f.write(res1[0] + "    " + res1[1])
            f.write("\r")

    # result = re.sub(r'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', '\r\n', title_name)
    # print(result)
    # result = re.sub(r'</?\w+[^>]*>', '', title_name)
    # for kk in result:
    #     print(kk)

    # print(res1[0]  + "======" + res1[1])


# 添加任务数据
def mysql_db_task():
    # 打开数据库连接，不指定数据库
    conn = pymysql.connect('localhost', 'root', '123456')
    conn.select_db('answer_db')
    cur = conn.cursor()  # 获取游标

    # 配置等级数据
    # data = [{"id": 1, "answernum": 10}]
    # ddd = 0
    # for i in range(2, 80):
    #     step = 10 * i + 20
    #     ddd = ddd + step
    #     stepd = {"id": i, "answernum": ddd}
    #     data.append(stepd)

    # 提现列表配置
    # data = [{"level": 1, "withdrawal": 3000}, {"level": 2, "withdrawal": 3500}, {"level": 3, "withdrawal": 4000},
    #     #         {"level": 0, "withdrawal": 3000000}, {"level": 0, "withdrawal": 4000000},
    #     #          {"level": 0, "withdrawal": 5000000}, {"level": 0, "withdrawal": 6000000}]

    # 签到配置表
    data = [{"day": 1, "money": 100, "txnum": 0}]
    for i in range(1, 31):
        dd = {"day": i, "money": random.randint(100, 588), "txnum": 1 if i==30 or i==15 else 0}
        data.append(dd)


    jsonStr = json.dumps(data)
    print(jsonStr)

    sql = "insert into s_config (resourecsid,_values,remark) values('{}','{}','{}')".format(
        30, jsonStr, "")
    print(len(sql))
    insert = cur.execute(sql)
    print('添加语句受影响的行数：', insert)

    cur.close()
    conn.commit()
    conn.close()
    print('sql执行成功')


if __name__ == '__main__':

    mysql_db_task()
    # addData1()
    # for index in range(3, 281):
    #     print(index)
    #     getInfo(index)
